package com.simple.utils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import com.simple.entity.XmlBean;

/**
 * 对xml配置文件进行解析
 * @author 李凯
 * @version v-1.0
 * @date 2017-8-20
 * */
public class XmlUtils {
	public XmlUtils(){}
	
	/**
	 * 对xml配置文件进行解析
	 * @author 李凯
	 * @version v-1.0
	 * @date 2017-8-20
	 * @param xmlPath
	 * @return Map<String,XmlBean>
	 * */
	public static Map<String,XmlBean> simpleXml(String xmlPath) throws Exception{
		SAXBuilder builder = new SAXBuilder();
		Document document = builder.build(new File(xmlPath));
		Element root = document.getRootElement();
		Element actionRoot = root.getChild("action-mapping");
		List<Element> actions = actionRoot.getChildren();
		Map<String,XmlBean> rmap = new HashMap<String,XmlBean>();
		for(Element action : actions){
			XmlBean xmlBean = new XmlBean();
			String name = action.getAttributeValue("name");
			Element actionForm = root.getChild("form-beans");
			List<Element> forms = actionForm.getChildren();
			for(Element form : forms){
				if(name.equals(form.getAttributeValue("name"))){
					String formclass = form.getAttributeValue("class");
					xmlBean.setFormClass(formclass);
					break;
				}
			}
			String path = action.getAttributeValue("path");
			xmlBean.setPath(path);
			String type = action.getAttributeValue("class");
			xmlBean.setActionClass(type);
			xmlBean.setBeanName(name);
			List<Element> forwards = action.getChildren();
			Map<String,String> map = new HashMap<String,String>();
			for(Element forward : forwards){
				String fname = forward.getAttributeValue("name");
				String fvalue = forward.getAttributeValue("value");
				map.put(fname, fvalue);
			}
			xmlBean.setActionForward(map);
			rmap.put(path, xmlBean);
		}
		return rmap;
	}
}
